﻿using System.ServiceModel.Dispatcher;
using Budget.Core.Data;
using Microsoft.Practices.ServiceLocation;

namespace Budget.Wcf.Core.Transactions
{
    public class TransactionManager : IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            var transaction = ServiceLocator.Current.GetInstance<INHibernateTransaction>();
            transaction.Begin();
            return null;
        }

        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            var transaction = ServiceLocator.Current.GetInstance<INHibernateTransaction>();

            if (transaction.IsActive)
            {
                if (reply.IsFault)
                {
                    transaction.Rollback();
                }
                else
                {
                    transaction.Commit();
                }
            }
        }
    }
}